import createDOM from '@antv/dom-util/lib/create-dom'
import modifyCSS from '@antv/dom-util/lib/modify-css'
import Canvas from '@antv/g-base/lib/abstract/canvas';
import { IGraph } from '../../interface/graph';
import { ViewPortEventParam } from '../../types';
import Base from '../base'

// 网格背景图片
const GRID_PNG =
  'url()';

export default class Grid extends Base {
  public init() {
    const graph: IGraph = this.get('graph');
    const minZoom = graph.get<number>('minZoom');
    const graphContainer = graph.get<HTMLDivElement>('container');
    const canvas: HTMLDivElement = graph.get<Canvas>('canvas').get('el');
    const width = graph.get<number>('width');
    const height: number = graph.get<number>('height');

    const container: HTMLDivElement = createDOM(
      `<div style="position: absolute; left:0;top:0;right:0;bottom:0;overflow: hidden;z-index: -1;"></div>`
    );

    const gridContainer: HTMLDivElement = createDOM(
      `<div 
        class='g6-grid' 
        style='position:absolute;transform-origin: 0% 0% 0px; background-image: ${GRID_PNG}'></div>`
    );

    container.appendChild(gridContainer);

    modifyCSS(gridContainer, {
      width: `${width / minZoom}px`,
      height: `${height / minZoom}px`,
      left: 0,
      top: 0
    });

    graphContainer.insertBefore(container, canvas);

    this.set('container', container);
    this.set('gridContainer', gridContainer);
  }

  public getEvents() {
    return { 
      viewportchange: 'updateGrid' 
    };
  }

  /**
   * viewportchange 事件的响应函数
   * @param param 
   */
  protected updateGrid(param: ViewPortEventParam) {
    const gridContainer:HTMLDivElement = this.get('gridContainer');
    const matrix = param.matrix;

    const transform = `matrix(${matrix[0]}, ${matrix[1]}, ${matrix[3]}, ${matrix[4]}, 0, 0)`
    
    modifyCSS(gridContainer, {
      transform
    });
  }

  public getContainer(): HTMLDivElement {
    return this.get('container');
  }

  public destroy() {
    const graph: IGraph = this.get('graph')
    const graphContainer = graph.get<HTMLDivElement>('container');
    const container: HTMLDivElement = this.get('container')

    graphContainer.removeChild(container);
  }
}
